﻿using CheemsControl.Animations;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace CheemsControl.Controls
{
    public class PictureAutoLoadingBox : ScrollViewer
    {
        public PictureAutoLoadingBox()
        {
        }

        /// <summary>
        /// 图片资源
        /// </summary>
        public ObservableCollection<string> Source
        {
            get { return (ObservableCollection<string>)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(ObservableCollection<string>), typeof(PictureAutoLoadingBox), new PropertyMetadata(null, OnSourceChanged));



        /// <summary>
        /// 小box宽
        /// </summary>
        public double ItemWidth
        {
            get { return (double)GetValue(ItemWidthProperty); }
            set { SetValue(ItemWidthProperty, value); }
        }
        public static readonly DependencyProperty ItemWidthProperty =
            DependencyProperty.Register("ItemWidth", typeof(double), typeof(PictureAutoLoadingBox), new PropertyMetadata(60.0));


        /// <summary>
        /// 小box高
        /// </summary>
        public double ItemHeight
        {
            get { return (double)GetValue(ItemHeightProperty); }
            set { SetValue(ItemHeightProperty, value); }
        }
        public static readonly DependencyProperty ItemHeightProperty =
            DependencyProperty.Register("ItemHeight", typeof(double), typeof(PictureAutoLoadingBox), new PropertyMetadata(40.0));

        /// <summary>
        /// 小box背景色
        /// </summary>
        public System.Windows.Media.Brush ItemBackground
        {
            get { return (System.Windows.Media.Brush)GetValue(ItemBackgroundProperty); }
            set { SetValue(ItemBackgroundProperty, value); }
        }
        public static readonly DependencyProperty ItemBackgroundProperty =
            DependencyProperty.Register("ItemBackground", typeof(System.Windows.Media.Brush), typeof(PictureAutoLoadingBox), new PropertyMetadata(new SolidColorBrush(System.Windows.Media.Color.FromArgb(0x88, 0xDD, 0xDD, 0xDD))));

        /// <summary>
        /// 小box Margin
        /// </summary>
        public Thickness ItemMargin
        {
            get { return (Thickness)GetValue(ItemMargintItemMarginProperty); }
            set { SetValue(ItemMargintItemMarginProperty, value); }
        }
        public static readonly DependencyProperty ItemMargintItemMarginProperty =
            DependencyProperty.Register("ItemMargintItemMargin", typeof(Thickness), typeof(PictureAutoLoadingBox), new PropertyMetadata(new Thickness(2)));


        /// <summary>
        /// 小box 圆角
        /// </summary>
        public CornerRadius ItemCornerRadius
        {
            get { return (CornerRadius)GetValue(ItemCornerRadiusProperty); }
            set { SetValue(ItemCornerRadiusProperty, value); }
        }
        public static readonly DependencyProperty ItemCornerRadiusProperty =
            DependencyProperty.Register("ItemCornerRadius", typeof(CornerRadius), typeof(PictureAutoLoadingBox), new PropertyMetadata(new CornerRadius(2)));


        /// <summary>
        /// ToolTip放大比例
        /// </summary>
        public double ToolTipEnlargeScale
        {
            get { return (double)GetValue(ToolTipEnlargeScaleProperty); }
            set { SetValue(ToolTipEnlargeScaleProperty, value); }
        }
        public static readonly DependencyProperty ToolTipEnlargeScaleProperty =
            DependencyProperty.Register("ToolTipEnlargeScale", typeof(double), typeof(PictureAutoLoadingBox), new PropertyMetadata(5.0));




        /// <summary>
        /// 图片资源改变时
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PictureAutoLoadingBox thisControl = d as PictureAutoLoadingBox;

            thisControl.LoadVisibleImages();
        }
        private async void LoadVisibleImages()
        {
            // 获取当前可见区域的图片路径列表
            List<string> imagePathList = this.Source.Reverse().ToList();

            // 创建 ScrollViewer 和 WrapPanel
            ScrollViewer scrollViewer = new ScrollViewer();
            WrapPanel wrapPanel = new WrapPanel();

            scrollViewer.Content = wrapPanel;
            this.Content = scrollViewer;

            // 异步加载每个图片
            foreach (var imagePath in imagePathList)
            {
                await Task.Delay(1);
                // 异步加载图片
                await Task.Run(() => LoadImage(imagePath, wrapPanel));
            }
        }

        private void LoadImage(string imagePath, WrapPanel wrapPanel)
        {
            var resourceDictionary = new ResourceDictionary
            {
                Source = new Uri("pack://application:,,,/CheemsControl;component/Styles/Window/ImageDisplayWindowStyle.xaml", UriKind.Absolute)
            };
            // 确保在 UI 线程中创建 UI 元素
            Dispatcher.Invoke(async () =>
            {
                var border = new Border()
                {
                    Width = this.ItemWidth,
                    Height = this.ItemHeight,
                    Background = this.ItemBackground,
                    Margin = this.ItemMargin,
                    CornerRadius = this.ItemCornerRadius,
                };
                border.MouseLeftButtonDown += (sender, d) =>
                {
                    ImageDisplayWindow imageDisplayWindow = new ImageDisplayWindow()
                    {
                        Source = imagePath,
                        Style = (Style)resourceDictionary["ImageDisplayWindowStyle"],
                    };
                    imageDisplayWindow.ShowDialog();
                };

                // 动画效果
                AnimationHelper.ApplyMouseEnterAnimation(border, border.Width / 2, border.Height / 2, 1.25);

                var image = new System.Windows.Controls.Image()
                {
                    Margin = this.ItemMargin,
                    Source = new BitmapImage(new Uri(imagePath)),
                };

                border.Child = image;


                VisualBrush visualBrush = new VisualBrush(border);
                Border toolTipBorder = new Border()
                {
                    Background = visualBrush,
                    Width = this.ItemWidth * ToolTipEnlargeScale,
                    Height = this.ItemHeight * ToolTipEnlargeScale,
                };
                ToolTip tooltip = new ToolTip
                {
                    Background = new SolidColorBrush(System.Windows.Media.Colors.Transparent),
                    BorderBrush = new SolidColorBrush(System.Windows.Media.Colors.Transparent),
                    BorderThickness = new Thickness(0),
                    Content = toolTipBorder
                };

                // 设置 ToolTip 的显示行为
                border.ToolTip = tooltip;

                // 将控件添加到 WrapPanel 中
                wrapPanel.Children.Add(border);
            });
            
        }



    }
}
